<template>
  <!-- 客户库-新增客户 -->
  <div class="customerAddPage">
    <el-form
      :inline="true"
      :model="baseForm"
      ref="baseFormRef"
      :rules="baseState.rules"
      class="demo-form-inline"
      label-position="right"
      label-width="120px"
    >
      <el-row>
        <el-col :span="7">
          <el-form-item style="width: 100%" label="客户类型:" prop="type">
            <el-select
              v-model="baseForm.type"
              style="width: 100%"
              placeholder="选择客户类型"
              @change="typeChange"
            >
              <el-option
                v-for="item in baseState.typeOptionsArr"
                :key="item.type"
                :label="item.label"
                :value="item.type"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            style="width: 100%"
            label="合作客户名称:"
            label-width="200px"
            prop="customerName"
          >
            <el-input
              v-model="baseForm.customerName"
              maxlength="20"
              placeholder="请输入客户名称(20字以内)"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="1">
          <el-form-item
            style="width: 100%"
            label="营业执照号:"
            prop="licenseNumber"
          >
            <el-input
              v-model="baseForm.licenseNumber"
              clearable
              placeholder="请输入营业执照号"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="7">
          <el-form-item
            style="width: 100%"
            label="法人姓名:"
            prop="juridicalPerson"
          >
            <el-input
              v-model="baseForm.juridicalPerson"
              placeholder="请输入法人姓名"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            style="width: 100%"
            label-width="200px"
            label="负责人/授权代表人姓名:"
            prop="contactName"
          >
            <el-input
              v-model="baseForm.contactName"
              placeholder="请输入负责人姓名"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="1">
          <el-form-item style="width: 100%" label="身份证号:" prop="idNumber">
            <el-input
              v-model="baseForm.idNumber"
              clearable
              placeholder="请输入身份证号"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="7">
          <el-form-item
            style="width: 100%"
            label="联系电话:"
            prop="contactPhone"
          >
            <el-input
              v-model="baseForm.contactPhone"
              placeholder="请输入联系电话"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            style="width: 100%"
            label="品牌名称:"
            label-width="200px"
            prop="brandName"
          >
            <el-input
              v-model="baseForm.brandName"
              placeholder="请输入品牌名称"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-for="(n, i) in baseForm.list" :key="i">
        <el-col :span="7">
          <el-form-item
            style="width: 100%"
            :label="`账户名称 ${i + 1}:`"
            :prop="'list.' + i + '.bankAccountName'"
            :rules="{
              required: true,
              message: '请输入账户名称',
              trigger: 'blur',
            }"
          >
            <el-input
              v-model="n.bankAccountName"
              placeholder="请输入账户名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            style="width: 100%"
            :label="`银行账户号 ${i + 1}:`"
            label-width="200px"
            :prop="'list.' + i + '.bankAccountNumber'"
            :rules="{
              required: true,
              message: '请输入银行账户号',
              trigger: 'blur',
            }"
          >
            <!-- 银行账号为16-19位数 -->
            <el-input
              v-model="n.bankAccountNumber"
              clearable
              placeholder="请输入银行账户号"
              @input="
                n.bankAccountNumber = limitInputNum(
                  n.bankAccountNumber,
                  35,
                  0,
                  false
                )
              "
            />
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="1">
          <el-form-item
            style="width: 100%"
            :label="`开户行 ${i + 1}:`"
            :prop="'list.' + i + '.bankName'"
            :rules="{
              required: true,
              message: '请输入开户行',
              trigger: 'blur',
            }"
          >
            <el-input v-model="n.bankName" placeholder="请输入开户行名称" />
          </el-form-item>
        </el-col>
        <el-col :span="1" v-if="baseForm.list.length > 1 && i !== 0">
          <el-icon
            class="m-l10 cursor"
            style="margin-top: 7px"
            :size="20"
            @click="deletAccount(i)"
            ><Remove
          /></el-icon>
        </el-col>
      </el-row>
      <el-button
        plain
        class="accountAddStyle button_edit"
        @click="addAccount"
      >
        <el-icon style="margin-right: 5px; margin-top: 2px"><Plus /></el-icon>
        新增银行账户</el-button
      >
      <el-row>
        <el-col :span="15">
          <el-form-item style="width: 100%" label="通讯地址:" prop="address">
            <el-input
              type="textarea"
              style="padding-top: 7px"
              v-model="baseForm.address"
              clearable
              :autosize="{ minRows: 5, maxRows: 5 }"
              placeholder="请输入通讯地址"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="display: flex; justify-content: center">
        <el-button plain class="button_cancel2" style="width: 76px" @click="cancelAdd"
          >取消</el-button
        >
        <el-button
          class="button_view"
          style="width: 76px;"
          type="primary"
          :disabled="subDisFlag"
          @click="submitAdd"
        >
          确认
        </el-button>
      </el-row>
    </el-form>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref, watch} from "vue";
import {
  ElForm,
  ElFormItem,
  ElRow,
  ElCol,
  ElSelect,
  ElOption,
  ElMessage,
} from "element-plus";
import { Plus, Remove } from "@element-plus/icons-vue";
import {checkEmptyString, getURLhandler, limitInputNum} from "@/common/utils/GlobalUtils";
import { customerApi } from "@/api/assets";
import { useRoute, useRouter } from "vue-router";
import {useStore} from "vuex";
import {clearCache} from "@/utils/createRoutes";


const route = useRoute();
const getCustomerId = getURLhandler(route.path).id;
const pageType = getURLhandler(route.path).pageType;

const router = useRouter();

const store = useStore();
const subDisFlag = ref(false);
const baseFormRef = ref(null);
const baseForm = reactive({
  customerName: "",
  type: null,
  contactName: "",
  contactPhone: "",
  address: "",
  licenseNumber: "",
  idNumber: "",
  juridicalPerson: "",
  brandName: "",
  list: [
    {
      bankAccountName: "",
      bankAccountNumber: "",
      bankName: "",
    },
  ],
});

const checkPhone = (rule, value, callback) => {
  const reg = /^1[2|3|4|5|6|7|8|9][0-9]\d{8}$/;
  if (!value) {
    callback(new Error("请输入联系电话"));
  } else if (!reg.test(value)) {
    callback(new Error("请输入正确的手机号码格式"));
  } else {
    callback();
  }
};

const baseState = reactive({
  typeOptionsArr: [
    {
        type: 1,
        label: "个人",
    },
    {
      type: 2,
      label: "企业",
    },
     /* {
          type: 3,
          label: "个体户",
      },*/
      {
          type: 4,
          label: "政府机关",
      },
  ],
  rules: {
    type: [{ required: true, trigger: "change", message: "请选择客户类型" }],
    customerName: [{ required: true, trigger: "blur", message: "请输入客户名称" },
    {validator:checkEmptyString, trigger: "blur"}
    ],
  },
});

const typeChange = (val) => {
  let ruleObj = {
    // contactPhone: [{ validator: checkPhone, trigger: "blur" }],
    address: [{ required: true, trigger: "blur", message: "请输入通讯地址" }],
    idNumber: [{ required: true, trigger: "blur", message: "请输入身份证号" }],
    customerName: [
      { required: true, trigger: "blur", message: "请输入客户名称" },
    ],
    licenseNumber: [
      { required: true, trigger: "blur", message: "请输入营业执照号" },
    ],
    contactName: [
      { required: true, trigger: "blur", message: "请输入代表人姓名" },
    ],
  };
  if (val == 1) {
    // 个人。 不填：合作客户名称、 营业执照号、 代表人姓名、法人姓名
    delete ruleObj.customerName;
    delete ruleObj.licenseNumber;
    delete ruleObj.contactName;
    // delete ruleObj.juridicalPerson;
  } else {
    // 企业。 不填：法人姓名、 身份证号
    // delete ruleObj.juridicalPerson;
    delete ruleObj.idNumber;
  }
  baseFormRef.value.clearValidate();
  baseState.rules = ruleObj;
  baseState.rules.type = [
    { required: true, trigger: "change", message: "请选择客户类型" },
  ];
};
const cancelAdd = () => {
  clearCache({title:'新增客户'});
  router.push({ path: "/asset/company/customerInformation" });
};

// 新增银行账户
const addAccount = () => {
  if (baseForm.list.length == 3) {
    ElMessage.warning("最多只能添加三条！");
  } else {
    baseForm.list.push({
      bankAccountName: "",
      bankAccountNumber: "",
      bankName: "",
    });
  }
};
const deletAccount = (index) => {
  baseForm.list.splice(index, 1);
};

// 提交
const submitAdd = () => {
  baseFormRef.value.validate((vaild) => {
    if (vaild) {
      subDisFlag.value = true;
      let params = { ...baseForm };
      if (pageType === "add") { // 新增
        customerApi.customerAdd(params).then((res) => {
          const { code } = res;
          if (code == 200) {
            ElMessage.success("新增客户成功");
            setTimeout(() => {
              router.push({ path: "/asset/company/customerInformation" });
              subDisFlag.value = false;
            }, 1000);
            clearCache({title:'新增客户'});
          } else {
            subDisFlag.value = false;
          }
        });
      } else { // 编辑
        customerApi.customerEdit(getCustomerId, params).then((res) => {
          const { code } = res;
          if (code === '200') {
            ElMessage.success("编辑客户信息成功");
            setTimeout(() => {
              router.push({ path: "/asset/company/customerInformation" });
              subDisFlag.value = false;
            }, 1000);
          } else {
            subDisFlag.value = false;
          }
        });
      }
    }
  });
};

/**
 * 监听form,用户在输入
 */
watch(baseForm,(value)=>{
    store.commit("setCustomForm", baseForm);
},{deep:true})

const initForm = () => {
    if (store.state.collaborativeApproval.customForm) {
        for (let key in store.state.collaborativeApproval.customForm) {
            for (let key2 in baseForm) {
                baseForm[key] = store.state.collaborativeApproval.customForm[key];
            }
        }
    }
};

// 编辑时获取信息
const initCustomerInfo = (id) => {
  customerApi.getCustomerInfo(id).then((res) => {
    const { code, data } = res;
    Object.keys(baseForm).forEach((key) => {
      if (key !== "list") {
        baseForm[key] = data[key] !== null && data[key] !== "" ? data[key] : "";
      } else {
        if (data[key] && data[key].length > 0) {
          baseForm[key] = data[key];
        } else {
          baseForm[key] = [{
            bankAccountName: "",
            bankAccountNumber: "",
            bankName: "",
          }];
        }
      }
    });
  });
};

onMounted(() => {
  if (pageType === "edit") {
    initCustomerInfo(getCustomerId);
  }
  if(pageType !=='edit'){
      initForm();
  }
});
</script>

<style lang="scss" scoped>
.customerAddPage {
  .accountAddStyle {
    margin-left: 120px;
    margin-bottom: 34px;
  }
}
</style>

<style lang="scss" scoped>
.customerAddPage {
  .demo-form-inline {
    .el-form-item {
      margin-bottom: 34px;
      .el-form-item__label {
        font-weight: 500;
        font-size: 16px;
        font-family: SourceHanSansMedium;
      }
      .el-form-item__content {
        .el-date-editor.el-input,
        .el-date-editor.el-input__wrapper {
          width: 100%;
          .el-input__wrapper {
            width: 100%;
          }
        }
      }
    }
    .noBgBox {
      .el-form-item__content {
        background: none;
      }
    }
  }
}
</style>
